package mytf.core.toolbox;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
 

/**
 * @author chuc
 *
 */
@SuppressWarnings("deprecation")
public class DownAsFile {
	
	private static String filePath = "D:\\MYTFDOWN\\";
	public String getFileName(String url,String contentType){
		if(url==null && url.length()<8 ){
			return "-1";
		}
		url = url.substring(7);
		if(contentType.indexOf("html")!= -1){
			return url.replaceAll("[\\?/:*|<>+\"]", "_")+".html";//regex 替换掉括号里面的字符为"_"
		}else{
			return url.replaceAll("[\\?/:*|<>\"]", "_")+"."+
			contentType.substring(contentType.indexOf("/")+1);
		}
	}
	
	public void save2Local(InputStream instream,String filePath){
		try{
			DataOutputStream  out  = new DataOutputStream(
					new FileOutputStream (new File(filePath)));
			byte buffer[]=new byte[1024];
			while((instream.read(buffer))!=-1){
				out.write(buffer);
			}
			out.flush();
			out.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public String downFile(String url){
		
		HttpClient httpclient = new  DefaultHttpClient(); 
		HttpGet httpget = new HttpGet(url);
		try {
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) { 
				InputStream instream = entity.getContent(); 
				try {
//					?do something useful  
					String filePath = this.filePath + this.getFileName(url, entity.getContentType().getValue());
					this.save2Local(instream, filePath);
				} finally {
					instream.close();
				}
			}
			
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return "";
		
	}
	
	
	
	
	
}
